﻿using System.Drawing;
using System;

namespace HurlBat.XEdit2D
{
    public static class Util
    {
        public static Bitmap Crop(Image img, Rectangle bounds)
        {
            Bitmap cropped = new Bitmap(bounds.Width, bounds.Height);
            Graphics g = Graphics.FromImage(cropped);
            g.DrawImage(img, new Rectangle(0, 0, bounds.Width, bounds.Height),
                bounds, GraphicsUnit.Pixel);
            return cropped;
        }
        public static Bitmap MakeSquare(Image img)
        {
            int size = Math.Max(img.Size.Width, img.Size.Height);
            Bitmap cropped = new Bitmap(size, size);
            Graphics g = Graphics.FromImage(cropped);
            g.DrawImage(img,
                new Rectangle((size - img.Size.Width) / 2, 
                    (size - img.Size.Height) / 2, img.Size.Width, img.Size.Height),
                new Rectangle(0, 0, img.Size.Width, img.Size.Height),
                GraphicsUnit.Pixel);
            return cropped;
        }
        public static Color AverageColor(Bitmap original)
        {
            float[] ret = new float[3]{0f,0f,0f};
            int totalPixels = original.Width * original.Height;

            for (int i = 0; i < original.Width; i++)
                for (int j = 0; j < original.Height; j++)
                {
                    Color col = original.GetPixel(i, j);
                    ret[0] += col.R;
                    ret[1] += col.G;
                    ret[2] += col.B;
                }
            ret[0] /= totalPixels;
            ret[1] /= totalPixels;
            ret[2] /= totalPixels;
            return Color.FromArgb(Convert.ToByte(ret[0]), Convert.ToByte(ret[1]), Convert.ToByte(ret[2]));
        }
    }
}
